package hong.jun.pet_home.controller.org;


import hong.jun.basic.util.AjaxResult;
import hong.jun.basic.util.PageList;
import hong.jun.pet_home.domain.org.Employee;
import hong.jun.pet_home.query.EmployeeQuery;
import hong.jun.pet_home.service.org.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * restfull风格
 *
 * @Controller
 * @ResponseBody
 */

@RestController
@RequestMapping("/employee")
//@CrossOrigin//后台的跨域解决方案-spring4.2.5及以上版本支持
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Employee employee) {
        //判断有无id决定新增还是修改
        try {
            if (employee.getId() != null) {
                employeeService.update(employee);
            } else {
                employeeService.save(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /* 根据id 删除  */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        try {
            //System.out.println(id);
            Employee employee = employeeService.getById(id);
            System.out.println("删除" + employee.toString());//未查到对象为空会报空指针异常
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    //根据id 批量删除
    @PostMapping("/dels")
    public AjaxResult dels(@RequestBody Long[] ids) {
        try {
            //System.out.println(Arrays.toString(ids));
            employeeService.deletes(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /*根据Id查询*/
    @GetMapping(value = "/{id}")
    public Employee getById(@PathVariable("id") Long id) {
        return employeeService.getById(id);
    }

    @GetMapping
    public List<Employee> getAll() {
        return employeeService.getAll();
    }

    /*条件分页查询*/
    @PostMapping
    public PageList<Employee> getPage(@RequestBody EmployeeQuery query) {
        //System.out.println("条件"+query);
        return employeeService.queryPage(query);
    }
}
